package signGrammar.controller;

import java.util.ArrayList;

import javax.swing.JComponent;
import javax.swing.JLabel;

import signGrammar.expressions.IGrammarExpression;
import signGrammar.expressions.util.CExpressionElement;
import signGrammar.expressions.util.CProductionsMap;
import signGrammar.expressions.util.EExpressionElementClass;
import signGrammar.view.CViewNonterminalButton;
import signGrammar.view.CViewNonterminalChoiceButton;
import signGrammar.view.CViewProduction;
import signGrammar.view.CViewNonterminalButton.INonterminalListener;
import signGrammar.view.CViewNonterminalChoiceButton.INonterminalChoiceListener;

public class CExpressionConverter {
	
	private String getScreenName(CExpressionElement e){
		return EExpressionElementClass.parseVarType( e.getValue() );
	}
	
	private String getCommand(CExpressionElement e){
		return e.getValue();
	}
	
	public JComponent[] convertToDeduction(IGrammarExpression expression, INonterminalListener listener ){
		ArrayList<JComponent> components = new ArrayList<JComponent>();
		for(CExpressionElement c : expression.toElements() ){
			if( c.is( EExpressionElementClass.NONTERMINAL_NAME ) )
				components.add( new CViewNonterminalButton(
					getCommand(c),
					getScreenName(c),
					listener
				));
			else
				if( c.is( EExpressionElementClass.VARIABLE_NAME ) )
					components.add( new JLabel( getScreenName(c) ) );					
				else
					components.add( new JLabel( getCommand(c) ) );
		}
		return components.toArray(new JComponent[ components.size() ]);
	}
	
	public JComponent[] convertToChoises(String key, IGrammarExpression[] grammarExpressions, INonterminalChoiceListener listener ){
		ArrayList<JComponent> components = new ArrayList<JComponent>();
		for( IGrammarExpression e : grammarExpressions )
			components.add( new CViewNonterminalChoiceButton(key,e, listener) );
		return components.toArray(new JComponent[ components.size() ]);
	}
	
	private String[] toString(IGrammarExpression[] extrs){
		String[] s = new String[ extrs.length ];
		for(int i=0; i<extrs.length; i++)
			s[i] = extrs[i].toString();
		return s;
	}
	
	public JComponent[] convertToProductions(CProductionsMap productionsMap){
		ArrayList<JComponent> components = new ArrayList<JComponent>();
		for( String key: productionsMap.getKeys() )
			components.add( new CViewProduction( key, toString( productionsMap.get(key) ) ) );
		return components.toArray(new JComponent[ components.size() ]);
	}
}
